package ex06.pyrmont.startup;

import ex06.pyrmont.core.SimpleContextV6;
import ex06.pyrmont.core.SimpleContextLifecycleListenerV6;
import ex06.pyrmont.core.SimpleContextMapperV6;
import ex06.pyrmont.core.SimpleLoaderV6;
import ex06.pyrmont.core.SimpleWrapperV6;
import org.apache.catalina.Connector;
import org.apache.catalina.Context;
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleListener;
import org.apache.catalina.Loader;
import org.apache.catalina.Mapper;
import org.apache.catalina.Wrapper;
import org.apache.catalina.connector.http.HttpConnector;

/**
 * 和第五章一样
 */
public final class BootstrapV6 {

    public static void main(String[] args) {

        Connector connector = new HttpConnector();
        ((HttpConnector) connector).setDebug(4);
        Wrapper wrapper1 = new SimpleWrapperV6();
        wrapper1.setName("PrimitiveServlet");
        wrapper1.setServletClass("PrimitiveServlet");
        Wrapper wrapper2 = new SimpleWrapperV6();
        wrapper2.setName("ModernServlet");
        wrapper2.setServletClass("ModernServlet");

        Context context = new SimpleContextV6();
        context.addChild(wrapper1);
        context.addChild(wrapper2);

        Mapper mapper = new SimpleContextMapperV6();
        mapper.setProtocol("http");
        LifecycleListener listener = new SimpleContextLifecycleListenerV6();
        ((Lifecycle) context).addLifecycleListener(listener);     //mark  这里想 context 配置了一个 lifeCycle 监听器 ;
        context.addMapper(mapper);
        Loader loader = new SimpleLoaderV6();
        context.setLoader(loader);
        // context.addServletMapping(pattern, name);
        context.addServletMapping("/servlet/PrimitiveServlet", "PrimitiveServlet");
        context.addServletMapping("/servlet/ModernServlet", "ModernServlet");
        connector.setContainer(context);
        try {
            connector.initialize();
            ((Lifecycle) connector).start();
            ((Lifecycle) context).start();

            // make the application wait until we press a key.
            System.in.read();
            ((Lifecycle) context).stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
